layui.extend({
    baseConfig: "/js/pages/baseConfig"
}).use(['form', 'layer', 'element', 'util', 'upload', 'baseConfig'], function () {
    var form = layui.form
    layer = parent.layer === undefined ? layui.layer : top.layer,
        laypage = layui.laypage,
        upload = layui.upload,
        layedit = layui.layedit,
        laydate = layui.laydate,
        baseConfig = layui.baseConfig,
        $ = layui.jquery;
    var imgFilePath = decodeURIComponent(getUrlParamer("imgFilePath"));
    var adminUserId = getUrlParamer("adminUserId");
    var companyId = getUrlParamer("companyId");
    var cooperativeName = getUrlParamer("cooperativeName");
    var id = getUrlParamer("id");
    // if (cooperativeName) {
    //     cooperativeName = window.atob(cooperativeName)
    // }
    if (imgFilePath) {
        handlemuliteImgs(imgFilePath);
    }

    //加载员工列表
    function loadUserSelect(companyId) {
        $.get("/userAdmin/listForSelect", function (res) {
            users = res;
            var sel = $("select[name=adminUserId]");
            sel.empty();
            for (var i = 0; i < users.length; i++) {
                var user = users[i];
                $(sel).append("<option value=\"" + user.id + "\">" + user.jobNumber + "</option> ")
            }
            //更新渲染
            form.render("select");
            if (companyId) {
                console.log("选中companyId", companyId)
                $(sel).val(companyId);
                loadCooperative(companyId);
            }
            form.render('select');
        });
    };
    loadUserSelect(companyId);
    //监听员工下拉
    form.on("select(adminUserId)", function (item) {
        //重新加载对应员工关联的供应商
        loadCooperative(item.value);
    });

    //加载供应商列表
    function loadCooperative(adminUserId) {
        $.get("/cooperativeNumber/listForSelectByUserId?userId=" + adminUserId, function (res) {
            var cooperativeNumbers = res.data;
            var sel = $("select[name=cooperativeName]");
            sel.empty();
            for (var i = 0; i < cooperativeNumbers.length; i++) {
                var cooperativeNumberModel = cooperativeNumbers[i];
                if (!cooperativeNumberModel.name) {
                    continue;
                }
                sel.append("<option value=\"" + cooperativeNumberModel.name + "\">" + cooperativeNumberModel.name + "</option> ")
            }
            //更新渲染
            form.render("select");
            console.log('默认的供应商名称1', cooperativeName)
            sel.val('');
            if (cooperativeName) {
                console.log('默认的供应商名称2', cooperativeName)
                sel.val(cooperativeName);
            }
            form.render("select");
        });
    }

    //监听next
    $("#nextFlag").click(function() {
        var index = top.layer.msg('自动加载下一条待编辑数据', {icon: 16, time: false, shade: 0.8});
        let id = $("#id").val();
        nextShow(id, index);
    })

    //监听提交
    form.on("submit(saveAndNextBtn)", function (data) {
        console.log('---->saveAndNextBtn data', data);
        var content = [];
        $('input[type=checkbox]:checked').each(function () {
            content.push($(this).val());
        });
        //获取系统参数里面配置的tva税率
        $.get("/systemparam/get/",
            function (res) {
                if (res.code == 200) {
                    if (!check(res, data)) {
                        return;
                    }
                    //弹出loadingsubmit
                    var index = top.layer.msg('数据提交中，请稍候, 成功后自动加载下一条待编辑数据', {icon: 16, time: false, shade: 0.8});
                    //提交数据
                    $.post("/cloudDisk/addOrUpdate", {
                        id: data.field.id,
                        name: data.field.name,
                        contentType: data.field.contentType,
                        entireContent: data.field.entireContent,
                        mount: data.field.mount,
                        customHouse: data.field.customHouse,
                        originFileUrl: data.field.originFileUrl,
                        imgFileUrl: data.field.imgFileUrl,
                        cooperativeName: data.field.cooperativeName,
                        invoiceNum: data.field.invoiceNum,
                        htMount: data.field.htMount,
                        tvaTwenty: data.field.tvaTwenty,
                        tvaTen: data.field.tvaTen,
                        tvaFive: data.field.tvaFive,
                        tvaTwo: data.field.tvaTwo,
                        tvaZero: data.field.tvaZero,
                        htTwenty: data.field.htTwenty,
                        htTen: data.field.htTen,
                        htFive: data.field.htFive,
                        htTwo: data.field.htTwo,
                        htZero: data.field.htZero,
                        manullyDate: data.field.manullyDate,
                        adminUserId: data.field.adminUserId
                    }, function (res) {
                        if (res.code == 200) {
                            top.layer.close(index);
                            top.layer.msg(res.msg);
                            nextShow(data.field.id, index);
                        } else {
                            top.layer.close(index);
                            if (res.msg == '日期出错') {
                                top.layer.msg("日期出错！");
                            } else {
                                top.layer.msg("后台计算失败，请联系管理员处理！");
                            }
                        }
                    });
                }
            }
        );
    });

    function nextShow(id, index) {
        // 查询,渲染
        var body = $("#childrenBody");
        if (id) {
            $.get("/cloudDisk/getNext/unDeal/" + id, function (res) {
                if (res.code == 200) {
                    if (res.data) {
                        body.find("input[name=id]").val(res.data.id);//
                        body.find("input[name=name]").val(res.data.name);
                        body.find("input[name=nom]").val(res.data.nom);
                        body.find("input[name=prenom]").val(res.data.prenom);
                        body.find("input[name=htMount]").val(res.data.htMount);
                        body.find("input[name=invoiceNum]").val("");
                        body.find("input[name=mount]").val(res.data.mount);
                        body.find("input[name=htTwenty]").val(res.data.htTwenty);
                        body.find("input[name=htTen]").val(res.data.htTen);
                        body.find("input[name=htFive]").val(res.data.htFive);
                        body.find("input[name=htTwo]").val(res.data.htTwo);
                        body.find("input[name=htZero]").val(res.data.htZero);
                        body.find("input[name=manullyDate]").val(res.data.manullyDate);
                        body.find("select[name=contentType]").val(res.data.contentType);
                        body.find("input[name=entireContent]").val(res.data.entireContent);
                        // 重新渲染图片
                        handlemuliteImgs(res.data.imgFileUrl);
                        console.log('下一条数据加载重新，重新渲染jobNumber')
                        loadUserSelect(res.data.companyId);
                        form.render();
                        setTimeout(function () {
                            top.layer.close(index);
                        }, 2000);
                    } else {
                        top.layer.msg("下一条待编辑的数据不存在");
                        setTimeout(function () {
                            top.layer.close(index);
                        }, 2000);
                    }
                } else {
                    top.layer.error("后台接口错误，请联系管理员处理！");
                    setTimeout(function () {
                        top.layer.close(index);
                    }, 2000);
                }
            });
        }
    };

    function check(res, data) {
        var tva20Rate = res.data.tva20Rate ? parseFloat(res.data.tva20Rate) : 0;
        var tva10Rate = res.data.tva10Rate ? parseFloat(res.data.tva10Rate) : 0;
        var tva5Rate = res.data.tva5Rate ? parseFloat(res.data.tva5Rate) : 0;
        var tva2Rate = res.data.tva2Rate ? parseFloat(res.data.tva2Rate) : 0;
        var tva0Rate = res.data.tva0Rate ? parseFloat(res.data.tva0Rate) : 0;
        var mount = data.field.mount ? parseFloat(data.field.mount) : 0;
        var htTwenty = data.field.htTwenty ? parseFloat(data.field.htTwenty) : 0;
        var htTen = data.field.htTen ? parseFloat(data.field.htTen) : 0;
        var htFive = data.field.htFive ? parseFloat(data.field.htFive) : 0;
        var htTwo = data.field.htTwo ? parseFloat(data.field.htTwo) : 0;
        var htZero = data.field.htZero ? parseFloat(data.field.htZero) : 0;
        var count = Math.round(((1 + tva20Rate) * htTwenty) * 100) / 100
            + Math.round(((1 + tva10Rate) * htTen) * 100) / 100
            + Math.round(((1 + tva5Rate) * htFive) * 100) / 100
            + Math.round(((1 + tva2Rate) * htTwo) * 100) / 100
            + Math.round(((1 + tva0Rate) * htZero) * 100) / 100
        count = Math.round(count * 100) / 100;
        let targetItem= [(count-0.01).toFixed(2), count.toFixed(2), (count+0.01).toFixed(2)];
        if (targetItem.indexOf(mount.toFixed(2)) == -1) {
            top.layer.msg("HT数字出错！！！！");
            return false;
        }
        if (data.field.contentType && data.field.contentType==3 && !data.field.adminUserId) {
            top.layer.msg("公司不能为空！！！！");
            return false;
        }
        if (data.field.contentType && data.field.contentType==3 && !data.field.cooperativeName) {
            top.layer.msg("供应商不能为空！！！！");
            return false;
        }
        return true;
    };

    //处理多张图片如何显示的问题
    function handlemuliteImgs(imgFilePath) {
        var imgFilePaths = imgFilePath.split(";");
        var imgDivStr = "";
        for (var i=0; i < imgFilePaths.length; i++) {
            var imgFilePath = imgFilePaths[i];
            if (imgFilePath) {
                imgFilePath += '?a=' + new Date().getTime();
                if (imgFilePath && imgFilePath != "") {
                    imgDivStr += "<img class='clouddisk_pdfImg_class' src=\"" + imgFilePath + "\" id=\"pdfImg" + (i + 1) + "\"/><br/>";
                }
            }
        }
        console.log("imgDivStr", imgDivStr);
        //清空并重新填充数据
        $("#cloudFileImgDiv").html("");
        $("#cloudFileImgDiv").html(imgDivStr);
    };
    //绑定校验
    form.verify({
        originFileUrl: function (val) {
            if (!val) {
                return "文件路径不能为空";
            }
        },
        mount: function (val) {
            if (!val) {
                if (val.toString().split(".").length > 2) {
                    return "金额最多只能有两位小数";
                }
            }
        },
        htMount: function (val) {
            if (val) {
                if (val.toString().split(".").length > 2) {
                    return "金额最多只能有两位小数";
                }
            }
        },
        htTwenty: function (val) {
            if (val) {
                if (val.toString().split(".").length > 2) {
                    return "金额最多只能有两位小数";
                }
            }

        },
        htTen: function (val) {
            if (val) {
                if (val.toString().split(".").length > 2) {
                    return "金额最多只能有两位小数";
                }
            }

        },
        htFive: function (val) {
            if (val) {
                if (val.toString().split(".").length > 2) {
                    return "金额最多只能有两位小数";
                }
            }

        },
        htTwo: function (val) {
            if (val) {
                if (val.toString().split(".").length > 2) {
                    return "金额最多只能有两位小数";
                }
            }
        },
        htZero: function (val) {
            if (val) {
                if (val.toString().split(".").length > 2) {
                    return "金额最多只能有两位小数";
                }
            }
        },
        manullyDate: function (val) {
            if (val) {
                if (val.length != 6) {
                    return "日期必须为010721这种格式";
                }
            } else {
                return "日期不能为空";
            }
        }
    });
    //上传文件
    upload.render({
        elem: '.uploadCloudFile',
        url: '/file/uploadCloudFile?type=uploadCloudFile',
        method: "post",
        accept: "file",
        exts: "pdf",
        done: function (res) {
            if (res.code == 200) {
                //隐藏的值不变
                $("input[name=originFileUrl]").val(res.data.pdfFilePath);
                $("input[name=imgFileUrl]").val(res.data.imgFilePaths);
                handlemuliteImgs(res.data.imgFilePaths);

                //给表单项赋值
                var analyseContent = res.data.analyseContent;
                $("input[name=entireContent]").val(analyseContent.entireContent);
            }
        }
    });
});
